//
//  ChatViewController.m
//  RingLetter
//
//  Created by dllo on 16/3/17.
//  Copyright © 2016年 FenglyNuo. All rights reserved.
//

#import "ChatViewController.h"


@interface ChatViewController ()<UITableViewDataSource,UITableViewDelegate,EMChatManagerDelegate,UIScrollViewDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) ChatConsoleView *chatConsoleView;

//会话类
@property (nonatomic, strong) EMConversation * conversation;

@end

@implementation ChatViewController

/*
 整个逻辑: 就是围绕发送和接收消息
 1.页面只有tableview和输入框
 2.首先获取已经会话的内容     [self reloadChatRecords];
 3.当发送消息时通过 [weakSelf sendMessageWithDraftText:draftText];方法
 4.当实时接收消息时通过 协议代理方法
 [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:dispatch_get_main_queue()];
 - (void)didReceiveMessage:(EMMessage *)message {
 然后刷新当前页的会话内容 [self reloadChatRecords];
 在reloadChatRecords中获取会话对象conversation,会话对象的属性conversation.loadAllMessages是数组存放所有会话内容
 
 
 涉及到两个类:
 1.消息类: EMChatText EMTextMessageBody EMMessage  .chatManager 用来发送消息
 2.会话类: EMConversation 存储所有聊天内容
 */


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor yellowColor];
    
    self.title = self.chatter;
    
    [self createUI];
    
    // 获取会话的记录
    [self reloadChatRecords];
    
    // 实时监听 ---- 接收消息
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    [self registerForKeyboardNotifications];
    
    /*
     UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
     [self.chatTableView addGestureRecognizer:tap];
     //    因为我自定义了UITableViewCell,里面会有一些按钮之类的控件，如果点到这些控件上时，键盘并不会退出。需把tap手势的cancelsTouchesInView设置为NO
     tap.cancelsTouchesInView =NO;
     */
}

- (void)createUI {
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:(UITableViewStylePlain)];
    [self.view addSubview:_tableView];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.and.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view).offset(-40);
    }];
    
    [self.tableView registerClass:[ChatTableViewCell class] forCellReuseIdentifier:@"ChatTableViewCell"];
    [self.tableView registerClass:[MyChatTableViewCell class] forCellReuseIdentifier:@"MyChatTableViewCell"];
    
    // 拖动时隐藏键盘
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.tableView setAllowsSelection:NO];
    
    //聊天页面的输入框
    self.chatConsoleView = [[ChatConsoleView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 40, self.view.frame.size.width, 40)];
    __weak typeof(self) weakSelf = self;
    
    // block回调 点击发送按钮触发 得到输入框中的字符串
    self.chatConsoleView.buttonClicked = ^(NSString *deaftText) {
        // 发送给环信服务器
        [weakSelf sendMessageWithDraftText:deaftText];
    };
    
    [self.view addSubview:self.chatConsoleView];
}



#pragma mark -- 2.发送消息
- (void)sendMessageWithDraftText:(NSString *)draftText {
    // 要发送的消息
    EMChatText *chatText = [[EMChatText alloc] initWithText:draftText];
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithChatObject:chatText];
    EMMessage *message = [[EMMessage alloc] initWithReceiver:self.chatter bodies:@[body]];
    message.messageType = eMessageTypeChat; // 设置为单聊消息
    //**********以上是在sdk文档中有*****
    
    // 发送消息
    [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil prepare:^(EMMessage *message, EMError *error) {
        
        // 准备发送
    } onQueue:dispatch_get_main_queue() completion:^(EMMessage *message, EMError *error) {
        
        // 发送完成后就立马获取会话刷新列表
        [self reloadChatRecords];
        
    } onQueue:dispatch_get_main_queue()];
}




#pragma mark -- 3.刷新数据
- (void)reloadChatRecords {
    //新建/获取一个会话
    //onversationForChatter:获取或创建与self.chatter的会话
    //conversationType:会话类型
    self.conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:self.chatter conversationType:eConversationTypeChat];
    
    NSLog(@"===========%ld",self.conversation.loadAllMessages.count);
    
    [self.tableView reloadData];
    
    
    if ([self.conversation loadAllMessages].count > 0) {
        
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.conversation loadAllMessages].count - 1 inSection:0] atScrollPosition:(UITableViewScrollPositionBottom) animated:YES];
    }
}



#pragma mark - tableView Delegate & DataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.conversation.loadAllMessages.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    EMMessage *message = self.conversation.loadAllMessages[indexPath.row];
    
    //    ChatTableViewCell *cell = nil;
    
    if ([message.to isEqualToString:self.chatter]) {
        
        MyChatTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"MyChatTableViewCell"];
        cell.message = message;
        return cell;
        
    }
    ChatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatTableViewCell"];
    cell.message = message;
    return cell;
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    EMMessage *message = [self.conversation.loadAllMessages objectAtIndex:indexPath.row];
    EMTextMessageBody *body = [message.messageBodies lastObject];
    
    CGFloat height = [ChatTableViewCell heightForCell:body.text];
    
    return height + 50;
}



#pragma mark - 注册通知中心
/**
 *  注册通知中心
 */
- (void)registerForKeyboardNotifications
{
    // 使用NSNotificationCenter 注册观察当键盘要出现时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didKeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    // 使用NSNotificationCenter 注册观察当键盘要隐藏时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}



/**
 *  键盘将要弹出
 *
 *  @param notification 通知
 */
- (void)didKeyboardWillShow:(NSNotification *)notification {
    
    NSLog(@"键盘弹起");
    
    NSDictionary * info = [notification userInfo];
    
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    NSLog(@"000000000=%f", keyboardSize.height);
    
    //输入框位置动画加载
    [self begainMoveUpAnimation:keyboardSize.height];
    
}

/**
 *  键盘将要隐藏
 *
 *  @param notification 通知
 */
- (void)didKeyboardWillHide:(NSNotification *)notification {
    
    NSLog(@"键盘消失");
    [self begainMoveUpAnimation:0];
    
    
}

/**
 *  开始执行键盘改变后对应视图的变化
 *
 *  @param height 键盘的高度
 */
- (void)begainMoveUpAnimation:(CGFloat)height {
    
    [UIView animateWithDuration:0.3 animations:^{
        
        [self.chatConsoleView setFrame:CGRectMake(0, self.view.frame.size.height - (height + 40), self.chatConsoleView.frame.size.width, self.chatConsoleView.frame.size.height)];
        
        //        CGRect frame = self.chatTableView.frame;
        //        frame.size.height = 667 - height - 40;
        //        self.chatTableView.frame = frame;
        
        
        
    }];
    
    //update更新约束
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        
        if (height == 0) {
            
            make.bottom.mas_equalTo(self.view).offset(-40);
            
        }else
        {
            make.bottom.mas_equalTo(self.view).offset(-height -40);
            
        }
        
    }];
    //更新约束,带动画效果
    [self.tableView layoutIfNeeded];
    
    
    if ([self.conversation loadAllMessages].count > 1) {
        
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.conversation.loadAllMessages.count - 1 inSection:0] atScrollPosition:(UITableViewScrollPositionTop) animated:YES];
    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
